/**
 * 
 */
package com.ciukes.dynosgi.jruby;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.jruby.Ruby.FileFinder;
import org.jruby.runtime.load.LoadServiceResource;
import org.osgi.framework.Bundle;

class EclipseBundleFileFinder implements FileFinder {

	private static final String BUNDLE = "bundle:";
	private final Collection<Bundle> searchInBundles;
	private final Map<String, java.net.URL> resolvedResourceCache;

	public EclipseBundleFileFinder(Collection<Bundle> searchInBundles) {
		this.searchInBundles = searchInBundles;
		resolvedResourceCache = new HashMap<String, java.net.URL>();
	}

	@Override
	public LoadServiceResource find(String name) {
		LoadServiceResource result = null;
		if (name.startsWith(BUNDLE)) {
			for (Bundle bundle : searchInBundles) {
				result = findWithinBundle(name, bundle);
				if (result != null) {
					break;
				}
			}
		}
		return result;
	}

	private LoadServiceResource findWithinBundle(String name, Bundle bundle) {
		LoadServiceResource result = null;
		if (resolvedResourceCache.containsKey(name)) {
			java.net.URL javaUrl = resolvedResourceCache.get(name);
			result = new LoadServiceResource(javaUrl, name);
		} else {
			String fileName = name.substring(BUNDLE.length());
			URL entry = bundle.getEntry(fileName);

			if (entry != null) {
				try {
					java.net.URL javaUrl = new URL(entry.toExternalForm());
					resolvedResourceCache.put(name, javaUrl);
					result = new LoadServiceResource(javaUrl, name);
				} catch (MalformedURLException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}
}